class QueryBuildings extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            buildings: [],
            devNumForCardDevice: 0,
            cardDeviceBindingList : []
        }

        this.page = 1;
    }


    search(){
        this.refs.table.refresh();
    }

    /**
     * 先按楼栋排序，再按单元排序
     * @param a
     * @param b
     * @returns {number}
     */
    sortBuilding(a,b){
        let first = parseInt(a.areaName) - parseInt(b.areaName);
        if(first != 0)
            return first;
        return parseInt(a.buildingName) - parseInt(b.buildingName);
    }

    updateBuildingList(page,pageSize) {
        console.log("this.props.commCode",this.props.commCode);
        let commCode = this.refs.commSelect.commCode;
        if(!this.initialized && this.props.commCode){
            commCode = this.props.commCode;
            this.initialized = true;
            console.log("this.props.commCode2",this.props.commCode);
        }
        let params = {};
        params.page = page;
        params.pageSize = pageSize;
        params.commCode = commCode;
        params.areaName = this.refs.areaName.value;
        params.buildingName = this.refs.buildingName.value;
        postJson("/building/query.x", params, (data) => {
            this.pageCount = data.data.size;
            this.setState({
                commCode:commCode,
                buildings: data.data.list.sort((a, b) => this.sortBuilding(a, b))
            });
        });
    }

    modify(building) {
        layui.layer.confirm('确实要修改该单元？', (index) => {
            let param = {
                BuildingCode: building.buildingCode,
                unitNumber: building.unitNumber,
                roomNumber: building.roomNumber,
                devNumber: building.devNumber,
                areaAliasName:building.areaAliasName,
                areaName:building.areaName,
                buildingAliasName:building.buildingAliasName,
                buildingType: building.buildingType
            }
            postJson("/building/modify.x", $.param(param),  (data) =>{
                layui.layer.msg("修改成功!");
                this.refs.table.refresh();
            });
            layui.layer.close(index);
        });
    }

    inputChange(e,index,value){
        this.state.buildings[index][value] = e.target.value;
        this.setState({});
    }

    modifyAll(){
        this.commSelectAssert();
        let commCode = this.refs.commSelect.commCode;
        let floors = this.refs.floorsBatch.value;
        let rooms = this.refs.roomsBatch.value;
        console.log("floor"+floors);
        if(!floors && !rooms){
            layui.layer.msg("数据不能为空")
            return;
        }

        layui.layer.confirm("确定要将"+(floors?"整个小区的楼层数修改为["+floors+"]":"")+(rooms?" 每层房间数都修改为["+rooms+"]":"")+"吗?",()=>{
            let params = {
                commCode : commCode,
                floors : floors,
                rooms : rooms
            }
            postJson("/building/modifyCommFloorAndRoom.x",params,(data)=>{
                layui.layer.msg("修改成功!");
                this.refs.table.refresh();
            });
        })
    }

    modifySelected(){
        let checkedValues = this.refs.table.checkboxValue;
        if(checkedValues.length == 0){
            layui.layer.msg("请选择一条数据");
            return;
        }

        let floors = this.refs.floorsBatch.value;
        let rooms = this.refs.roomsBatch.value;
        let params = [];

        for(let i = 0; i< checkedValues.length;i++){
            if(floors)
                checkedValues[i].unitNumber = floors;
            if(rooms)
                checkedValues[i].roomNumber = rooms;

            params.push(this.convertBuildingForSubmit(checkedValues[i]));
        }

        layui.layer.confirm("确认要修改所选数据么?",()=>{
            postRJson("/building/modifyBatchs.x",JSON.stringify(params),()=>{
                layui.layer.msg("修改成功!");
                this.refs.table.refresh();
            })
        })
    }

    deleteAll(){
        this.commSelectAssert();
        let commCode = this.refs.commSelect.commCode;
        layui.layer.confirm("确定删除整个小区的数据么?",()=>{
            postJson("/building/removeByComm.x",{commCode : commCode},()=>{
                layui.layer.msg("删除成功");
                this.refs.table.refresh();
            })
        })
    }

    deleteSelected(){
        let checkedValues = this.refs.table.checkboxValue;
        if(checkedValues.length == 0){
            layui.layer.msg("请选择一条数据");
            return;
        }

        layui.layer.confirm("确定删除所选数据么?",()=>{
            postRJson("/building/remove.x",JSON.stringify(checkedValues),()=>{
                layui.layer.msg("删除成功");
                this.refs.table.checkboxValue = [];
                this.refs.table.refresh();
            })
        })
    }

    convertBuildingForSubmit(building){
        return {
            buildingCode : building.buildingCode,
            areaName : building.areaName,
            areaAliasName : building.areaAliasName,
            sectionName : building.sectionName,
            buildingAliasName : building.buildingAliasName,
            unitNumber : building.unitNumber,
            roomNumber : building.roomNumber,
            devNumber : building.devNumber,
            buildingType: building.buildingType
        }
    }

    getBuildingObjectByCode(buildingCode){
        for(let i=0; i<this.state.buildings.length; i++){
            if(this.state.buildings[i].buildingCode == buildingCode){
                return this.state.buildings[i];
            }
        }
    }

    commSelectAssert(){
        let commCode = this.refs.commSelect.commCode;
        if(!commCode){
            layui.layer.msg("请选择小区");
            throw "error";
        }
    }

    newBuilding(){
        this.commSelectAssert();
        let commName = this.refs.commSelect.commText;
        let commCode = this.refs.commSelect.commCode;
        parent.layer.open({
            type: 2,
            skin: 'layui-layer-demo', //样式类名
            closeBtn: 0, //不显示关闭按钮
            shadeClose: true, //开启遮罩关闭
            fix: false,
            offset: '100px',
            area: ['1100px','220px'],
            title: '【'+commName + '】 楼栋单元添加-(如果小区只有一个区,区域不填.如果楼栋不是插入的，楼栋编号可不填，会自增)',
            content: '/BuildingCtrl/insertBuildings.x?commCode=' + commCode + '&commName=' + commName,
            success: function (layero, index) {
                layer.iframeAuto(index);
            }
        });
    }

    delete(buildingCode){
        let params = [];
        params.push(buildingCode);
        layui.layer.confirm("确定删除所选数据么?",()=>{
            postRJson("/building/remove.x",JSON.stringify(params),()=>{
                layui.layer.msg("删除成功");
                this.refs.table.refresh();
            })
        })
    }

    getCardBindingDev(devNumber){
        let cardDevTemp = this.cardUnitStr + appendZero(devNumber);
        let datas = this.state.cardDeviceBindingList;
        for(let i=0; i < datas.length; i++){
            if(datas[i].cardDeviceNumber === cardDevTemp)
                return datas[i];
        }

        let thisDev = {
            unit : this.unitStr,
            cardDeviceNumber : cardDevTemp
        };

        datas.push(thisDev);
        return thisDev;
    }

    assignCardDevice(building){
        this.cardUnitStr = appendZero(building.areaName) + appendZero(building.buildingName) + "00";
        this.unitStr = building.commCode + appendZero(building.areaName) + appendZero(building.buildingName);

        postJson("/cardDoorDevice/getBindings.x",{unitStr:this.unitStr},(data)=>{
            this.state.cardDeviceBindingList = data.data;
            this.setState({devNumForCardDevice:building.devNumber},()=>{
                this.refs.modalCardDevice.show();
            })
        })

    }

    cardDeviceCheck(checked,i){
        let cardDev = this.getCardBindingDev(i);
        /* 假如选中，给个默认值绑定设备01 */
        cardDev.device = checked?this.cardUnitStr + "01":null;

        this.setState({cardDeviceBindingList:this.state.cardDeviceBindingList});
    }

    cardDeviceBindingOnChange(value,i,devNumber){
        if(parseInt(value) > devNumber){
            return false;
        }
        let cardDev = this.getCardBindingDev(i);
        cardDev.device = this.cardUnitStr + appendZero(value);
        this.setState({cardDeviceBindingList:this.state.cardDeviceBindingList});
    }

    getCardDeviceItems(devNumber){
        let items = [];
        for(let i=1; i <= devNumber; i++){
            let cardDevObj = this.getCardBindingDev(i);
            items.push (
                <Item>
                    <Label>设备编号</Label>
                    <Input readonly="readonly" value={i} width="xs"/>
                    <Checkbox width="sm" onClick={(checked)=>this.cardDeviceCheck(checked,i)} checked={!!cardDevObj.device} title="副门禁"/>
                    <Input width="xs" value={cardDevObj.device?cardDevObj.device.substr(7,8):''} onChange={(value)=>this.cardDeviceBindingOnChange(value,i,devNumber)}
                           style={cardDevObj.device?{marginLeft:10}:{display:'none'}} type="number" max={devNumber}/>
                </Item>
            );
        }

        return items;
    }

    submitCardDevice(){
        let dataForSubmit = [];
        for(let i=0; i < this.state.cardDeviceBindingList.length; i++){
            if(this.state.cardDeviceBindingList[i].id || this.state.cardDeviceBindingList[i].device)
                dataForSubmit.push(this.state.cardDeviceBindingList[i]);
        }

        if(this.state.cardDeviceBindingList.length > 0) {
            postRJson("/cardDoorDevice/saveBindings.x", JSON.stringify(dataForSubmit), () => {
                layui.layer.msg("保存成功");
                this.refs.modalCardDevice.close();
            })
        }
    }

    onChangeComm(comm){
        console.log("comm",comm);
        this.setState({commCode:comm});
        this.refs.table.refresh();
    }

    getTableToolBar(){
        return (
            [
                [
                    <Input size="sm" width="sm" name="floorsBatch" ref="floorsBatch" placeholder="楼层数" frameStyle={{float:'left',marginRight:10}}/>,
                    <Input size="sm" width="sm" name="roomsBatch" ref="roomsBatch" placeholder="每层房间数" frameStyle={{float:'left',marginRight:10}}/>,
                    <div className="dropup pull-left">
                        <Button btnType="sm" className="dropdown-toggle" type="button" id="dropdownMenu2" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                            修改
                            <span className="caret"></span>
                        </Button>
                        <ul className="dropdown-menu" aria-labelledby="dropdownMenu2">
                            <li>
                                <a href="#" onClick={()=>this.modifyAll()}>修改全小区</a>
                                <a href="#" onClick={()=>this.modifySelected()}>修改所选项</a>
                            </li>
                        </ul>
                    </div>,
                    <div className="dropup pull-left" style={{marginLeft:10}}>
                        <Button btnType="danger" size="sm" className="dropdown-toggle" id="dropdownMenu2" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
                            删除
                            <span className="caret"></span>
                        </Button>
                        <ul className="dropdown-menu" aria-labelledby="dropdownMenu2">
                            <li>
                                <a href="#" onClick={()=>this.deleteAll()}>删除全小区</a>
                                <a href="#" onClick={()=>this.deleteSelected()}>删除所选项</a>
                            </li>
                        </ul>
                    </div>
                ]
            ]
        )
    }

    render(){
        console.log("state comm",this.state.commCode);
        return (
        <Frame header="单元信息列表">
            <Form type="pane">
                <Item>
                    <Label>小区名称</Label>
                    <LayuiCommSelect mask={['building', 'unit', 'floor', 'room']} commCode={this.state.commCode}
                                     ref="commSelect" onChangeComm={(comm)=>this.onChangeComm(comm)}/>

                    <Label>栋号</Label>
                    <Input name="areaName" ref="areaName"/>

                    <Label>单元</Label>
                    <Input name="buildingName" ref="buildingName"/>

                    <Button btnType="normal" onClick={()=>this.search()}>
                        <i className="layui-icon" style={{verticalAlign:"middle"}}>&#xe615;</i>查询
                    </Button>

                    <Button btnType="normal" onClick={()=>this.newBuilding()}>
                        <i className="layui-icon" style={{verticalAlign:"middle"}}>&#xe608;</i>新增楼栋
                    </Button>
                </Item>
                <Table ref="table"
                       checkboxRenderCallback={()=>{this.setState({})}}
                       checkboxKeyname="buildingCode"
                       pageData={this.state.buildings}
                       count = {this.pageCount}
                       pageOnClick = {(page,pageSize)=>this.updateBuildingList(page,pageSize)}
                       toolbar = {
                           this.getTableToolBar()
                       }
                >
                    <thead>
                        <tr>
                            <th width={70}>
                                <TCheckbox checkall={true} tableRef={this.refs.table}/>&nbsp;&nbsp;全选
                            </th>
                            <th>小区名称</th>
                            <th>区域</th>
                            <th width={70}>栋数编号</th>
                            <th>栋数别名</th>
                            <th width={70}>单元编号</th>
                            <th>单元别名</th>
                            <th>类型</th>
                            <th width={70}>每栋楼层</th>
                            <th width={70}>每层房间数</th>
                            <th width={70}>每单元设备数</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                    {
                        this.state.buildings.map((building,index)=>{
                            return (
                                <tr>
                                    <td>
                                        <TCheckbox data={building} tableRef={this.refs.table}/>
                                    </td>
                                    <td>{building.commName}</td>
                                    <td>{building.sectionName}</td>
                                    <td><input type="text" style={{width: 70}} value={building.areaName} onChange={(e)=>this.inputChange(e,index,'areaName')}/></td>
                                    <td><input type="text" value={building.areaAliasName} onChange={(e)=>this.inputChange(e,index,'areaAliasName')}/></td>
                                    <td>{building.buildingName}</td>
                                    <td><input type="text" value={building.buildingAliasName?building.buildingAliasName:''} onChange={(e)=>this.inputChange(e,index,'buildingAliasName')}/></td>
                                    <td>{building.buildingType === 1 ? '别墅' : '普通单元'}</td>
                                    <td><input style={{width: 70}} type="text" value={building.unitNumber} onChange={(e)=>this.inputChange(e,index,'unitNumber')}/></td>
                                    <td><input style={{width: 70}} type="text" value={building.roomNumber} onChange={(e)=>this.inputChange(e,index,'roomNumber')}/></td>
                                    <td><input style={{width: 70}} type="text" value={building.devNumber} onChange={(e)=>this.inputChange(e,index,'devNumber')}/></td>
                                    <td>
                                        <Button btnType="danger" size="xs" onClick={()=>this.delete(building)}>删除</Button>
                                        <Button btnType="normal" size="xs" onClick={()=>this.modify(building)}>修改</Button>
                                        <Button size="xs" onClick={()=>this.assignCardDevice(building)}>分配副门禁</Button>
                                    </td>
                                </tr>
                            )
                        })
                    }
                    </tbody>
                </Table>

            </Form>
            <Modal title="副门禁绑定" ref="modalCardDevice" area={['427px']}>
                <Form size="sm" type="pane" style={{marginLeft:10}}>
                {
                    this.getCardDeviceItems(this.state.devNumForCardDevice)
                }
                <Item>
                    <Button size="sm" formBtn="true" onClick={()=>this.submitCardDevice()}>确定</Button>
                    &nbsp;&nbsp;
                    <Tips>{'1.假如哪个设备是副门禁,比如设备编号2，请点击副门禁复选框,然后填入该副门禁所属主机的设备编号,比如设备编号1,'+
                            '此时即表名设备编号2的设备不是梯口机，而是一个刷卡设备，它通过485与设备编号1的梯口机连接，由它管理数据。<br/>'+
                           '2.假如选择了设备编号2,绑定的主机也选择设备编号2,说明编号2同时存在梯口机与副门禁,此时默认副门禁作为内门门禁使用,'+
                            '而梯口机作为外门门禁使用。'}
                        </Tips>
                </Item>
                </Form>
            </Modal>
        </Frame>
        )
    }
}

ReactDOM.render(<QueryBuildings commCode={getUrlParam("commCode")}/>,document.getElementById("queryBuildings"));